use std::collections::HashMap;
use log::debug;

///http响应模块
pub struct HttpResponse {
    pub version: String,
    pub status_code: String,
    pub status_info: String,
    pub headers: HashMap<String, String>,
    pub body: Option<String>,
}

impl HttpResponse {
    pub fn new() -> HttpResponse {
        HttpResponse {
            version: "HTTP/1.1".to_string(),
            status_code: "200".to_string(),
            status_info: "OK".to_string(),
            headers: HashMap::new(),
            body: None,
        }
    }
    pub fn set_code(mut self, status_code: &str) -> Self {
        self.status_code = status_code.to_string();
        self.status_info = match self.status_code.as_str() {
            "200" => "OK".to_string(),
            "400" => "Bad Request".to_string(),
            "404" => "Not Found".to_string(),
            _ => { "Internal Server Error".to_string() }
        };
        self
    }
    pub fn set_body(mut self, body: String) -> Self {
        self.body = Some(body);
        self
    }
    pub fn add_header(mut self, key: &str, value: &str) -> Self {
        self.headers.insert(key.to_string(), value.to_string());
        self
    }
    pub fn generate(&self) -> String {
        let mut response = "".to_string();
        response += &[self.version.clone(), self.status_code.clone(), self.status_info.clone()].join(" ");
        for (k, v) in self.headers.clone() {
            response += "\r\n";
            response += &[k, v].join(":");
        }
        debug!("Response Header:\n{}",response);
        response += "\r\n\r\n";
        if let Some(s) = &self.body {
            response += s;
        }
        response
    }
}